<!--  -->
<template>
  <div>
    <el-button class="mb-4" @click="getUserInfo">获取数据</el-button>
    <BasicTable :table-data="tableData" :columns="columns"> </BasicTable>

    <el-descriptions class="mt-4" title="数据统计" :column="3" border>
      <el-descriptions-item width="200">
        <template #label>
          <div class="cell-item">
            <!-- <el-icon :style="iconStyle">
              <user />
            </el-icon> -->
            现水晶价格
          </div>
        </template>
        <el-input v-model="stoneValue" />
      </el-descriptions-item>
      <el-descriptions-item width="200">
        <template #label>
          <div class="cell-item">
            <!-- <el-icon :style="iconStyle">
              <iphone />
            </el-icon> -->
            每天生产数量
          </div>
        </template>
        <el-input v-model="createStoneNum" />
      </el-descriptions-item>
      <el-descriptions-item width="200">
        <template #label>
          <div class="cell-item">已交易数量</div>
        </template>
        {{ totalStone }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">
            <!-- <el-icon :style="iconStyle">
              <user />
            </el-icon> -->
            已有水晶数量
          </div>
        </template>
        {{ stoneCount }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">
            <!-- <el-icon :style="iconStyle">
              <iphone />
            </el-icon> -->
            可交易水晶数
          </div>
        </template>
        {{ stoneCount2 }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">价值</div>
        </template>
        {{ stoneValueCount }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">总支出</div>
        </template>
        {{ props.payValue }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">总收入</div>
        </template>
        {{ props.incomeValue }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">利润</div>
        </template>
        {{ profit }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">预计需要多少水晶回本</div>
        </template>
        {{ needStoneNum }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">预计需要多少天</div>
        </template>
        {{ needDays }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">利润+可以卖出</div>
        </template>
        {{ profit + stoneValueCount }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">预计-已有水晶</div>
        </template>
        {{ needStoneNum - stoneCount }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">实际天数</div>
        </template>
        {{ (needStoneNum - stoneCount) / 11 }}
      </el-descriptions-item>
    </el-descriptions>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import BasicTable from '@/components/table/Index.vue'
import {
  findUserProfileApi,
  findUserPrivateMapMachineCountApi,
  giveRecordApi,
  orderListApi
} from '@/api/home'

const props = defineProps({
  payValue: {
    require: true,
    default: () => 0
  },
  incomeValue: {
    require: true,
    default: () => 0
  },
  unitPrice: {
    default: 0
  }
})
const tableData = ref([
  {
    tel: '13295916310',
    token:
      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnYW1lZmktc2VydmVyIiwic3ViIjoibG9naW4iLCJleHAiOjE2OTk0MzE2NTEsIm5iZiI6MTY5ODgyODY1MSwiaWF0IjoxNjk4ODI2ODUxLCJqdGkiOiJiZDkzOGI4My1hYTQ0LTRlMDMtOWYzZi00OTZiNjNhYmI3ZmYiLCJ1aWQiOjEwMDQ1MTg0fQ.GzUUR1EmK56u3oZd72POP9E_K-au2fGfiLXXI9_ZmHk'
  },
  {
    tel: '15376399240',
    token:
      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnYW1lZmktc2VydmVyIiwic3ViIjoibG9naW4iLCJleHAiOjE2OTk0MzUxMjUsIm5iZiI6MTY5ODgzMjEyNSwiaWF0IjoxNjk4ODMwMzI1LCJqdGkiOiI2YTAwY2FiMy0xOTFiLTRkZDktYTAyNi02MTcwZTUyNWY0ZTYiLCJ1aWQiOjEwMTczNzQyfQ.QBeDwh9THtoaX2RSWkOrxopGxhWSaXMYRLhBgN0sdBg'
  },
  {
    tel: '17374026917',
    token:
      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnYW1lZmktc2VydmVyIiwic3ViIjoibG9naW4iLCJleHAiOjE2OTk0MzYxMjYsIm5iZiI6MTY5ODgzMzEyNiwiaWF0IjoxNjk4ODMxMzI2LCJqdGkiOiJjNDc5NjI1OC04NmE5LTRmMGQtYjQzNS1iZGQ1MDJjMGY1MDkiLCJ1aWQiOjEwMTg1NTI0fQ.6C5FR9yyeq9aX9-0o30ZUNhP7wzb79yyEr5_lcYPElU'
  },
  {
    tel: '18243651228',
    token:
      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnYW1lZmktc2VydmVyIiwic3ViIjoibG9naW4iLCJleHAiOjE2OTg5Nzk0NDYsIm5iZiI6MTY5ODM3NjQ0NiwiaWF0IjoxNjk4Mzc0NjQ2LCJqdGkiOiIzMWQ0M2YyYy1hZjNmLTQwYjAtYjk4Zi1lNTExYTU3YmNmN2MiLCJ1aWQiOjEwMTk4NTAxfQ.eWDdKxuaPI_4slOlG1dhiCYgh9Nv3LDFmD6YXgwNSJE'
  },
  {
    tel: '',
    token:
      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnYW1lZmktc2VydmVyIiwic3ViIjoibG9naW4iLCJleHAiOjE2OTk3OTY2MTMsIm5iZiI6MTY5OTE5MzYxMywiaWF0IjoxNjk5MTkxODEzLCJqdGkiOiI2NjQyMTk5ZC02MjYzLTQ2ZjQtOTIyMS0xZWYzZGI1ZDk1ZTkiLCJ1aWQiOjEwMzExOTg3fQ.kT3d1eIQv07eNwJstUAxbiQWdlYll_B1Zex9MnAAW9w'
  }
])

const columns = ref([
  { prop: 'nickname', label: '用户名' },
  { prop: 'stone', label: '水晶数量' },
  { prop: 'totalStone', label: '已生产水晶数量' },
  { prop: 'changeCount', label: '卖出数量' },
  { prop: 'daysPassed', label: '游戏时间' },
  { prop: 'beginTime', label: '开始玩时间' },
  { prop: 'phone', label: '手机号码' }
])

onMounted(() => {
  getUserInfo()
})

const getUserInfo = async () => {
  await Promise.all(
    tableData.value.map(async (item) => {
      const [userInfo, stoneInfo, changeCount, timeInfo] = await Promise.all([
        findUserProfile(item),
        findUserPrivateMapMachineCount(item),
        giveRecord(item),
        getOrderList(item)
        // inviteCreate(item)
      ])
      item.phone = userInfo.phone
      item.nickname = userInfo.nickname
      item.inviteCode = userInfo.inviteCode
      item.stone = Number(stoneInfo.stone.toFixed(5))
      item.totalStone = Number(stoneInfo.totalStone.toFixed(5))
      item.rate = stoneInfo.rate
      item.allMachineCount = stoneInfo.allMachineCount
      item.onPrivateCount = stoneInfo.onPrivateCount
      item.changeCount = changeCount
      item.beginTime = timeInfo.formattedDate
      item.daysPassed = timeInfo.daysPassed
    })
  )
}

const findUserProfile = async (item) => {
  const { data } = await findUserProfileApi({}, item.token)
  return data
}

const findUserPrivateMapMachineCount = async (item) => {
  const { data } = await findUserPrivateMapMachineCountApi({}, item.token)
  return data
}

const giveRecord = async (item) => {
  const { data } = await giveRecordApi(
    {
      limit: 200,
      page: 1
    },
    item.token
  )
  let num = 0
  data.forEach((item) => {
    if (item.incomeType == 1) {
      num += item.changeCount
    }
  })
  return num
}

const getOrderList = async (item) => {
  const { data } = await orderListApi(
    {
      limit: 20,
      page: 1,
      state: 0
    },
    item.token
  )
  const length = data?.length || 0
  if (length) {
    return formatAndCalculateDaysPassed(data[length - 1].createdAt)
  }
  return ''
}

const formatAndCalculateDaysPassed = (isoDateString) => {
  const date = new Date(isoDateString)

  // Calculate the formatted date
  const formattedDate = formatDate(date)

  // Calculate the number of days passed
  const today = new Date()
  const timeDifference = today - date
  const daysPassed = Math.floor(timeDifference / (24 * 60 * 60 * 1000))

  return { formattedDate, daysPassed }
}

const formatDate = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// stoneCount为tableData.value.userStoneCount的和
const stoneCount = computed(() => {
  let count = 0
  tableData.value.forEach((item) => {
    if (item.stone) {
      count += item.stone
    }
  })
  return count.toFixed(6) // 保留六位小数
})

const stoneCount2 = computed(() => {
  let count = 0
  tableData.value.forEach((item) => {
    if (item.stone) {
      count += Math.floor(item.stone / 1.05)
    }
  })
  return count // 保留六位小数
})

const totalStone = computed(() => {
  let count = 0
  tableData.value.forEach((item) => {
    count += item.changeCount
  })
  return count // 保留六位小数
})

const stoneValue = ref(5)
watch(
  () => props.unitPrice,
  (newVal) => {
    stoneValue.value = newVal
  },
  {
    immediate: true
  }
)
const createStoneNum = ref(11)
const stoneValueCount = computed(() => {
  return stoneValue.value * stoneCount2.value
})
// const incomeValue = ref(0)
// const payValue = ref(0)
// const income = (val) => {
//   console.log(val, 'income')
//   incomeValue.value = val
// }

// const pay = (val) => {
//   payValue.value = val
// }

const profit = computed(() => {
  return parseFloat(props.incomeValue) - parseFloat(props.payValue)
})

const needStoneNum = computed(() => {
  return Math.abs(Math.floor(profit.value / stoneValue.value))
})
const needDays = computed(() => {
  return Math.ceil(needStoneNum.value / createStoneNum.value)
})
</script>

<style lang="scss" scoped></style>
